<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border scripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['dbbottom', index1 === 0 ? 'dbtop' : '', 'vcenter']"
              :key="index1"
              v-for="(item1, index1) in scope.row.children"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index2 === 0 ? '' : 'dbtop', 'vcenter']"
                  :key="index2"
                  v-for="(item2, index2) in item1.children"
                >
                  <!-- 利用for循环渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 利用v-for嵌套循环渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      :key="index3"
                      v-for="(item3, index3) in item2.children"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showSetRight(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        ref="addFormRef"
        :rules="addFormRules"
        :model="addForm"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色的对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        ref="editFormRef"
        :rules="editFormRules"
        :model="editForm"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightVisibleDialog"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        ref="treeRef"
        :data="rightlist"
        :props="treeProps"
        show-checkbox
        :default-expand-all="true"
        node-key="id"
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightVisibleDialog = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //所有角色列表数据
      rolesList: [],
      //控制添加角色的对话框的显示与隐藏
      addDialogVisible: false,
      //添加角色的表单数据
      addForm: {},
      //添加角色的表单验证对象
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 8,
            message: '角色名称在2~8个字符之间',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 1,
            max: 15,
            message: '角色描述长度在1~15个字符之间',
            trigger: 'blur',
          },
        ],
      },
      //控制编辑角色的对话框的显示与隐藏
      editDialogVisible: false,
      //编辑角色的表单数据
      editForm: {},
      //编辑角色的表单验证对象
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 8,
            message: '角色名称在2~8个字符之间',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 1,
            max: 15,
            message: '角色描述长度在1~15个字符之间',
            trigger: 'blur',
          },
        ],
      },
      //控制分配权限的对话框的显示与隐藏
      setRightVisibleDialog: false,
      //所有权限数据
      rightlist: [],
      treeProps: {
        children: 'children',
        label: 'authName',
      },
      //默认选中的权限的id
      defKeys: [],

      //保存当前角色的id
      roleId: '',
    }
  },
  created() {
    //获取所有角色列表的数据
    this.getRolesList()
  },
  methods: {
    //获取所有角色列表的数据
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表数据失败!')
      }
      this.rolesList = res.data
    },

    //关闭添加角色对话框发生的事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },

    //添加角色
    async addRoles() {
      const { data: res } = await this.$http.post('roles', this.addForm)
      if (res.meta.status !== 201) {
        return this.$message.error('添加角色失败!')
      }
      this.addDialogVisible = false
      this.getRolesList()
      this.$message.success('添加角色成功!')
    },

    //点击编辑按钮显示对话框,并且发送请求:根据id查询角色列表
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色信息失败!')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },

    //关闭编辑对话框触发的事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },

    //修改角色信息
    async editRoles() {
      const { data: res } = await this.$http.put(
        'roles/' + this.editForm.roleId,
        {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc,
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改角色信息失败!')
      }
      this.editDialogVisible = false
      this.getRolesList()
      this.$message.success('修改角色信息成功!')
    },
    //删除角色信息
    async deleteRoles(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (confirmResult != 'confirm') {
        return this.$message.info('取消删除角色')
      }
      //如果是confirm的话,就发送网络请求
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message.success('删除角色成功')
      this.getRolesList()
    },

    //根据权限id删除指定权限
    async removeRightById(role, id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除！')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${id}`
      )
      if (res.meta.status !== 200) {
        this.$message.error('删除失败！')
      }
      //只把下拉的刷新一下，刷新完成之后不会关闭下拉  所以把data返回的数据重新赋给权限
      role.children = res.data
    },

    //展示分配权限的对话框
    async showSetRight(role) {
      //把当前的角色id保存在data数据中
      this.roleId = role.id

      // 获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败！')
      }
      this.rightlist = res.data

      //递归获取三级权限的id
      this.getLeafKeys(role, this.defKeys)
      this.setRightVisibleDialog = true
    },
    //利用递归的方式获取三级权限的id
    getLeafKeys(node, arr) {
      //如果该node节点是三级权限，则没有children属性
      if (!node.children) {
        return arr.push(node.id)
      }
      //如果不是三级权限，则对他的孩子进行遍历
      node.children.forEach((item) => {
        return this.getLeafKeys(item, arr)
      })
    },

    //当关闭分配权限对话框时，清空默认勾选的id数组，这样，就不会再下一次显示之前的默认勾选
    setRightDialogClosed() {
      this.defKeys = []
    },

    /**
     * 给当前角色分配权限
     * 先获取所有被勾选和半选的权限id
     * 然后携程以，分割的字符串
     * 最后发送网络请求
     */
    async submit() {
      let keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      let idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightVisibleDialog = false
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.dbtop {
  border-top: 1px solid #eee;
}
.dbbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>